<template>
    <div>
        <!-- <searchForm :searchArr="searchArr" @onSubmit="onSubmit"></searchForm> -->
        <div class="gva-table-box gva-table-box1">
            <div class="role">
                <LTable
                    :columns="columns"
                    :tableData="tableData"
                    :pages="pages"
                    tableName="dddmsSpecDrawing"
                    @updateMultipleSelection="handleSelectionChange"
                    @changePages="changePages"
                    @rowDblclick="(row) => updateSbuProjectsFunc(row, 1)"
                    :maxHeight="'calc(100vh - 226px)'"
                    :searchArr="searchArr"
                    :isSearch="true"
                    @onSubmit="onSubmit"
                    :export="true"
                >
                    <template #action>
                        <div class="gva-btn-list" v-if="userStore.userInfo.authority?.authorityId !== 1000">
                            <el-button
                                type="primary"
                                icon="plus"
                                @click="openCreateAndEdit"
                                >新增</el-button
                            >
                            <el-button
                                icon="delete"
                                v-auth="btnAuth.batchDel"
                                style="margin-left: 10px"
                                :disabled="!multipleSelection.length"
                                @click="onDelete"
                                >删除</el-button
                            >
                            <relatedBtn
                                :disabled="multipleSelection.length != 1"
                                :row="
                                    multipleSelection.length == 1 &&
                                    multipleSelection[0]
                                "
                                :modalType="'ddmsSpecDrawing'"
                            />
                            <el-button
                                type="primary"
                                class="table-button"
                                :disabled="multipleSelection.length != 1"
                                @click="historyVision"
                            >
                                历史版本
                            </el-button>
                            <el-button
                                type="primary"
                                class="table-button"
                                @click="authApply"
                            >
                                图纸权限申请
                            </el-button>
                        </div>
                    </template>
                    
                    <template #CreatedAt="{ row }">
                        {{ formatDate(row.CreatedAt) }}
                    </template>
                    <template #UpdatedAt="{ row }">
                        {{ formatDate(row.UpdatedAt) }}
                    </template>
                    <template #displaySize="{ row }">
                        {{ row.displaySize?.value }}
                    </template>
                    <template #accessoryNumChild="{ row }">
                        <el-popover placement="right" :width="160">
                            <div>
                                <div v-for="item in row.accessoryNum">{{item}}</div>
                            </div>
                            <template #reference>
                                <div style="white-space:nowrap;text-overflow:ellipsis;overflow:hidden;">
                                    <span v-for="(item,i) in row.accessoryNum">{{item}},</span>
                                </div>
                            </template>
                        </el-popover>
                    </template>
                    <template #FirstCreatedAt="{row}">
         
         <span  v-if="row.FirstCreatedAt"> {{formatDate(row.FirstCreatedAt )=="1-01-01" ? '' : formatDate(row.FirstCreatedAt ) }}</span>
       </template>
                    <!-- <template #event>
                        <el-table-column
                            align="left"
                            label="操作"
                            fixed="right"
                            min-width="320"
                            width="320"
                        >
                            <template #default="scope">
                                <el-button
                                    type="primary"
                                    link
                                    icon="edit"
                                    class="table-button"
                                    @click="updateSbuProjectsFunc(scope.row)"
                                    >编辑</el-button
                                >
                                <el-button
                                    type="primary"
                                    link
                                    icon="delete"
                                    @click="deleteRow(scope.row)"
                                    >删除</el-button
                                >
                                <relatedBtn
                                    :row="scope.row"
                                    :modalType="'ddmsSpecDrawing'"
                                />
                                <el-button type="primary" link icon="discount"
                                    >历史版本</el-button
                                >
                            </template>
                        </el-table-column>
                    </template> -->
                </LTable>
            </div>
        </div>
        <el-dialog v-model="historyVisionShow" title="历史版本" width="900">
            <el-table
                ref="multipleTableRef"
                :data="historyList"
                @rowDblclick="rowDblclickFun"
                style="width: 100%"
            >
                <el-table-column prop="cumstomerNum" label="客戶編號" />
                <el-table-column prop="customerBrand" label="品牌" />
                <el-table-column prop="localStyleNum" label="本廠款號" />
                <el-table-column prop="drawingNum" label="圖紙編號" />
                <el-table-column prop="dataType" label="圖紙類型" />
                <el-table-column prop="" label="鏡架材質">
                    <template #default="scope">
                        {{ scope.row.extend?.frameMaterials }}
                    </template>
                </el-table-column>
                <el-table-column prop="displaySize" label="资料類型尺碼">
                    <template #default="scope">
                        <span v-if="scope.row.displaySize">
                            {{ scope.row.displaySize.label }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态">
                    <template #default="scope">
                        <span v-if="scope.row.status">
                            {{ scope.row.status==1 ? '已完成' :scope.row.status==0  ? '草稿'  : '审批中'}}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="structure" label="鏡架結構" />
                <!-- <el-table-column
                    prop="selfMadeAccessory"
                    label="自制配件(已選)"
                >
                    <template #default="scope">
                        <span v-if="scope.row.selfMadeAccessory">
                            {{
                                scope.row.selfMadeAccessory
                                    .map((item) => {
                                        return item.label;
                                    })
                                    .join(",")
                            }}
                        </span>
                    </template>
                </el-table-column> -->
                <el-table-column prop="version" label="版本" />
            </el-table>
        </el-dialog>
    </div>
</template>

<script setup>
import {
    createDdmsSpecDrawing,
    deleteDdmsSpecDrawing,
    deleteDdmsSpecDrawingByIds,
    updateDdmsSpecDrawing,
    findDdmsSpecDrawing,
    getDdmsSpecDrawingList,
    getDdmsSpecDrawingHistoryList,
} from "@/api/plmDdmsSpecDrawing";
import { getDrawingCategoryList } from "@/api/drawingCategory";
import { useUserStore } from "@/pinia/modules/user";
// 全量引入格式化工具 请按需保留
import {
    getDictFunc,
    formatDate,
    formatBoolean,
    filterDict,
    ReturnArrImg,
    onDownloadFile,
} from "@/utils/format";
import { useDict } from "@/utils/dictionary";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
// 引入组件
import LTable from "@/components/LTable/LTable.vue";
import { useI18n } from "vue-i18n";

const { t: il8n } = useI18n();

// 路由
const router = new useRouter();
const route = new useRoute();
const userStore = useUserStore();
import { useBtnAuth } from "@/utils/btnAuth";
const btnAuth = useBtnAuth();

defineOptions({
    name: "DdmsSpecDrawing",
});

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
    productSpecNum: "",
    projectNum: "",
    cumstomerNum: "",
    customerStyleNum: "",
    localStyleNum: "",
    updateUser: "",
});

// 验证规则
const rule = reactive({});

// =========== 表格控制部分 ===========
const searchInfo = ref({});
const tableData = ref([]);
const pages = ref({
    page: 1,
    pageSize: 20,
    total: 0,
});

// ======表格头部数据======
const columns = ref([
    {
        prop: "styleNum",
        label: "款式编号",
        fixedWidth: 130,
        show: true,
        filter: true,
        // slot: "styleNum",
        tableColumnProps: {
            fixed: "left",
        },
    },
    {
        prop: "cumstomerNum",
        fixedWidth: 130,
        label: "客户编号",
        show: true,
        filter: true,
    },
    {
        prop: "customerBrand",
        fixedWidth: 130,
        label: "品牌",
        show: true,
        filter: true,
    },
    {
        prop: "localStyleNum",
        fixedWidth: 160,
        label: "本厂款号",
        show: true,
        filter: true,
    },
    {
        prop: "customerStyleNum",
        fixedWidth: 120,
        label: "客户款号",
        show: true,
        filter: true,
    },
    {
        prop: "drawingCate",
        fixedWidth: 120,
        label: "图纸分类",
        show: true,
        filter: true,
    },
    {
        prop: "dataType",
        fixedWidth: 120,
        label: "资料类型",
        show: true,
        filter: true,
    },
    {
        prop: "frameMaterials",
        fixedWidth: 120,
        label: "镜架材质",
        show: true,
        filter: true,
        // tableColumnProps: {
        //     formatter: (row) => {
        //         if (row.extend) {
        //             return row.extend.frameMaterials;
        //         } else {
        //             return "";
        //         }
        //     },
        // },
    },
    {
        prop: "displaySize",
        fixedWidth: 130,
        label: "尺码",
        show: true,
        filter: true,
    },
    {
        prop: "drawingNum",
        width: 300,
        fixedWidth: 250,
        label: "图纸编号",
        show: true,
        filter: true,
        // slot: "drawingNum",
    },
    {
        prop: "version",
        fixedWidth: 90,
        label: "版本",
        show: true,
        filter: true,
    },
    {
        prop: "accessoryNum",
        width: 160,
        label: "自制配件（已选）",
        show: true,
        filter: true,
        childSlot:true,
        childSlotName:'accessoryNumChild'
    },
    {
        prop: "status",
        label: "状态",
        fixedWidth: 90,
        show: true,
        filter: true,
        // slot: "status",
    },
    {
        prop: "structure",
        fixedWidth: 120,
        label: "结构",
        show: true,
        filter: true,
    },
    {
        prop: "auditUser",
        label: "審批人",
        fixedWidth: 100,
        show: true,
        filter: true,
    },
    {
        prop: "CreatedAt",
        label: "创建时间",
        fixedWidth: 130,
        show: true,
        filter: true,
    },
    {
        prop: "createUser",
        label: "创建人",
        fixedWidth: 100,
        show: true,
        filter: true,
    },
    {
        prop: "UpdatedAt",
        label: "更新时间",
        fixedWidth: 130,
        show: true,
        filter: true,
    },
    {
        prop: "updateUser",
        label: "更新人",
        fixedWidth: 100,
        show: true,
        filter: true,
    },
    {
        prop: "FirstCreatedAt",
        label:'第一版本创建时间',
        show: true,
        fixedWidth: 150,
        // slot:"FirstCreatedAt"
    },
        // tableColumnProps: {
        //     formatter: (row) => formatDate(row.FirstCreatedAt),
        // },
]);

// ======查询数据======
const searchArr = ref([
    {
        prop: "styleNum",
        label: "款式编号",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "cumstomerNum",
        label: "客户编号",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "customerBrand",
        label: "品牌",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "displaySize",
        label: "尺码",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "localStyleNum",
        label: "本厂款号",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "customerStyleNum",
        label: "客户款号",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "drawingNum",
        label: "图纸编号",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "frameMaterials",
        label: "镜架材质",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "drawingCate",
        label: "图纸分类",
        show: true,
        value: undefined,
        type: "select",
        selectList: [],
    },
    {
        prop: "dataType",
        label: "资料类型",
        show: true,
        value: undefined,
        type: "select",
        selectList: [],
    },
    {
        prop: "structure",
        label: "结构",
        show: true,
        value: undefined,
        type: "select",
        selectList: [],
    },
    {
        prop: "status",
        label: "当前状态",
        show: true,
        value: undefined,
        type: "select",
        selectList: [
            { label: "草稿", value: "0" },
            { label: "完成", value: "1" },
            { label: "审批中", value: "2" },
        ],
    },
    {
        prop: "version",
        label: "版本",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "CreatedAt",
        label: "创建时间",
        show: true,
        value: "",
        type: "datetimerange",
    },
    {
        prop: "createUser",
        label: "创建人",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "UpdatedAt",
        label: "更新时间",
        show: true,
        value: "",
        type: "datetimerange",
    },
    {
        prop: "updateUser",
        label: "更新人",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "accessoryNum",
        label: "自制配件（已选）",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "auditUser",
        label: "審批人",
        value: "",
        type: "input",
        show: true,
    },
      {
      prop: "FirstCreatedAt",
      label: "第一版创建时间",
      show: true, // 通过 show 来控制列的展示或隐藏
      value: "",
      type: "datetimerange",
    },
]);

// 查询
const getTableData = async () => {
    const table = await getDdmsSpecDrawingList({
        page: pages.value.page,
        pageSize: pages.value.pageSize,
        ...searchInfo.value,
    });
    if (table.code === 0) {
        tableData.value = table.data.list.map((item) => {
            item.status =
                item.status == 1
                    ? "完成"
                    : item.status == 2
                    ? "审批中"
                    : "草稿";
            item["displaySize"] = item.displaySize?.value || "";
            item["frameMaterials"] = item.extend?.frameMaterials || "";
            item["accessoryNum"] = item.selfMadeAccessory
                ?.filter((item) => item.checked)
                .map((item, index) => {
                    return item.label
                })
            item.CreatedAt = item.CreatedAt ? formatDate(item.CreatedAt) : "";
            item.UpdatedAt = item.UpdatedAt ? formatDate(item.UpdatedAt) : "";
            item.FirstCreatedAt = formatDate(item.FirstCreatedAt)=="1-01-01" ? "" : formatDate(item.FirstCreatedAt);
            return item;
        });
        pages.value.total = table.data.total;
        pages.value.page = table.data.page;
        pages.value.pageSize = table.data.pageSize;
    }
};

// 重置
const onReset = () => {
    searchInfo.value = {};
    getTableData();
};

// 搜索
const onSubmit = (val) => {
    searchInfo.value = {
        ...val,
    };
    pages.value.page = 1;
    pages.value.pageSize = 20;
    getTableData();
};

// 改变页码
const changePages = (currentPages) => {
    pages.value = {
        ...pages.value,
        ...currentPages,
    };
    getTableData();
};

// getTableData();

// ============== 表格控制部分结束 ===============

// 多选数据
const multipleSelection = ref([]);
// 多选
const handleSelectionChange = (val) => {
    multipleSelection.value = val;
};

// 删除行
const deleteRow = (row) => {
    ElMessageBox.confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        deleteDdmsSpecDrawingFunc(row);
    });
};

// 多选删除
const onDelete = async () => {
    ElMessageBox.confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(async () => {
        const IDs = [];
        if (multipleSelection.value.length === 0) {
            ElMessage({
                type: "warning",
                message: "请选择要删除的数据",
            });
            return;
        }
        multipleSelection.value &&
            multipleSelection.value.map((item) => {
                IDs.push(item.ID);
            });
        const res = await deleteDdmsSpecDrawingByIds({ IDs });
        if (res.code === 0) {
            ElMessage({
                type: "success",
                message: "删除成功",
            });
            if (tableData.value.length === IDs.length && pages.value.page > 1) {
                pages.value.page--;
            }
            getTableData();
        }
    });
};

// 删除行
const deleteDdmsSpecDrawingFunc = async (row) => {
    const res = await deleteDdmsSpecDrawing({ ID: row.ID });
    if (res.code === 0) {
        ElMessage({
            type: "success",
            message: "删除成功",
        });
        if (tableData.value.length === 1 && pages.value.page > 1) {
            pages.value.page--;
        }
        getTableData();
    }
};

// 打开 新增、修改
const openCreateAndEdit = () => {
    router.push({
        path: "/layout/ddmsSpecDrawingView",
    });
};

// 更新行
const updateSbuProjectsFunc = async (row, isView = 0) => {
    router.push({
        path: "/layout/ddmsSpecDrawingView",
        query: {
            ddmsNum: row.ddmsNum,
            subTitle: row.drawingNum ? row.drawingNum : undefined,
            isView,
        },
    });
};

function authApply(params) {
    const path1 = ref(import.meta.env.VITE_BASE_PATH);
    const File = "/output/图纸申请权限表.xlsx";
    var xml = new XMLHttpRequest();
    xml.open("GET", path1.value + File, true);
    xml.responseType = "blob";
    xml.onload = function () {
        var url = window.URL.createObjectURL(xml.response);
        var a = document.createElement("a");
        a.href = url;
        a.download = "图纸申请权限表.xlsx";
        a.click();
    };
    xml.send();
}

// 历史版本shou
const historyVisionShow = ref(false);
let historyList = ref([]); // 历史版本数据
// 历史版本
const historyVision = () => {
    historyList.value = [];
    let sel = multipleSelection.value[0];
    historyVisionShow.value = true;
    getDdmsSpecDrawingHistoryList({ ddmsNum: sel.ddmsNum }).then((res) => {
        if (res.code == 0) {
            historyList.value = res.data.list;
        }
    });
};
const rowDblclickFun = (row, column) => {
    historyVisionShow.value = false;
    if(row.ID == historyList.value[0].ID){
        router.push({
            path: "/layout/ddmsSpecDrawingView",
            query: {
                ddmsNum: row.ddmsNum,
                subTitle: row.drawingNum ? row.drawingNum : undefined,
                isView:1,
            },
        });
    }else{
        router.push({
            path: "/layout/ddmsSpecDrawingView",
            query: {
                ddmsNum: row.ddmsNum,
                subTitle: row.drawingNum ? row.drawingNum : undefined,
                isView: 1,
                version: row.version,
            },
        });
    }
};

onMounted(async () => {
    let list = [];
    // 获取字典
    await useDict("structure", "drawingDataType").then((d) => {
        // 字典列表
        list = searchArr.value.map((item) => {
            if (item.prop == "structure") {
                item["selectList"] = [...d.structure];
            }
            if (item.prop == "dataType") {
                item["selectList"] = [...d.drawingDataType];
            }
            return item;
        });
    });
    // 获取图纸分类
    await getDrawingCategoryList({ page: 1, pageSize: 999 }).then((res) => {
        if (res.code === 0) {
            let index = searchArr.value.findIndex((val) => {
                return val.prop == "drawingCate";
            });
            let ll = res.data.list.map((item) => {
                return {
                    label: item.drawingCate,
                    value: item.drawingCate,
                    dataType: item.dataType,
                };
            });
            list[index].selectList = ll;
        }
    });
    searchArr.value = [];
    searchArr.value = [...list];
});

watch(() => route.path, (newPath, oldPath) => {
//   console.log('路由已变更：', `从 ${oldPath} 到 ${newPath}`);
    if(newPath == '/layout/ddmsSpecDrawing'){
        getTableData();
    }
},{immediate:true});

</script>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");
.gva-table-box1 {
    :deep(.cell) {
       word-break: break-all;
    }
}
</style>
